
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[EBAS_SP_GEM_KARAKTER]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[EBAS_SP_GEM_KARAKTER]
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS OFF 
GO

CREATE PROCEDURE [DBO].[EBAS_SP_GEM_KARAKTER] 
	@session varchar(255),
	@karakter varchar(255),
	@karakterSkala varchar(255)
WITH ENCRYPTION
AS
	DECLARE @rettighed int,
		@guid uniqueidentifier,
		@karakterSkalaGuid uniqueidentifier
	
	SET NOCOUNT ON

	CREATE TABLE #temp ( rett int )
	INSERT INTO #temp (rett)
	EXEC EBAS.DBO.EBAS_SP_SIKKERHED_VERIFICER_SESSION @session	

	SET @rettighed = (SELECT IsNull(MAX(rett),0) FROM #temp)
	
	IF 8 <= @rettighed 
	BEGIN
		SET @karakterSkalaGuid = ( SELECT GUID FROM EBAS_KARAKTER_SKALA
				 	   WHERE NAVN = @karakterSkala )
			
		IF NOT EXISTS (	SELECT 1 FROM EBAS_KARAKTER 
				WHERE KARAKTER = @karakter
				AND KARAKTER_SKALA_GUID = @karakterSkalaGuid )
		BEGIN
			SET @guid = newid()
			
			INSERT INTO EBAS_KARAKTER
				SELECT 	@guid, @karakter, @karakterSkalaGuid 
		END
		ELSE
		BEGIN
			SET @guid = (	SELECT GUID FROM EBAS_KARAKTER 
					WHERE KARAKTER = @karakter
					AND KARAKTER_SKALA_GUID = @karakterSkalaGuid )
			
			UPDATE 	EBAS_KARAKTER
			SET 	KARAKTER = @karakter, KARAKTER_SKALA_GUID = @karakterSkalaGuid
			WHERE	GUID = @guid
		END
	END

	SELECT 	K.GUID, K.KARAKTER, K.KARAKTER_SKALA_GUID, KS.NAVN, 
		1 AS ANTAL
	FROM 	EBAS_KARAKTER K, EBAS_KARAKTER_SKALA KS
	WHERE 	K.KARAKTER_SKALA_GUID = KS.GUID
	AND 	K.GUID = @guid
GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO
